package com.itheima.travel.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.travel.pojo.Route;
import com.itheima.travel.service.RouteService;
import com.itheima.travel.utils.BeanFactory;
import com.itheima.travel.utils.PageBean;
import com.itheima.travel.web.base.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/routeServlet")
public class RouteServlet extends BaseServlet {
    /**
     * 分页查询分类下的线路信息
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void findRouteByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        //1.获取pageSize和pageNumber值
        int pageSize = 10;
        int pageNumber = 1;
        try {
            pageSize = Integer.parseInt(request.getParameter("pageSize"));
        } catch (NumberFormatException e) {
            pageSize = 10;
        }
        try {
            pageNumber = Integer.parseInt(request.getParameter("pageNumber"));
        } catch (NumberFormatException e) {
            pageNumber = 1;
        }
        //2.获取请求携带的条件
        String cid = request.getParameter("cid");
        //3.调用service处理业务逻辑
        RouteService service = (RouteService)BeanFactory.getBean("RouteService");
        PageBean<Route> pb = service.findRouteByPage(pageSize,pageNumber,cid);
        //4.将查询结果转成json返回给浏览器
        ObjectMapper om = new ObjectMapper();
        String pbJson = om.writeValueAsString(pb);
        System.out.println(pbJson);
        response.getWriter().print(pbJson);
    }


}